<?php

namespace Home\Controller;

class ScriptsController extends HomeCoreController {
    
	public $Model = null;

    protected function _initialize(){
		
        parent::_initialize();
		
        $this->Model = D('Scripts');
		
    }
	
	public function index(){
		
		if(IS_AJAX){
						
			$search = I('get.search');
			
			if (!empty($search)){
				
                $map['scriptsname'] = array('like', "%$search%");
				
			}
			
			$map['uid'] = session(C('AUTH_KEYS'));
				
			$map['mid'] = session('gid');
			
			$page_size = 10;
			
			$count = $this->Model->where($map)->count();
			
			$Page = new \Think\Page($count, $page_size);
			
			$list = $this->Model
				->where($map)
				->order("id desc")
				->limit($Page->firstRow . ',' . $Page->listRows)
				->select();
						
			$str = $this->tojson($list, $count);
			
			echo $str;
			
			exit;
			
        }else{
            $this->display();
			
        }
		
    }
	
	public function add(){
		
		if(IS_POST){
			
			$post_data = I('post.');
			
			$data = $post_data['department'];
			
			$post_data['department'] = json_encode($post_data['department']);
			
			$post_data['pic'] = json_encode($post_data['pic']);
			
			$data = $this->Model->create($post_data);
			
			if($data){
				
				$result = $this->Model->update($data);
				
				if($result){
					
					echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
					
				}else{
					
					$error = $this->Model->getError();
					
					echo json_encode(array('info'=>$error, 'status'=>'n'));
					
				}
				
			}else{
				
				$error = $this->Model->getError();
				
				echo json_encode(array('info'=>$error, 'status'=>'n'));
				
			}
					
		}else{
			
			$map['uid'] = session(C('AUTH_KEYS'));
			
			$list = M('Department')->where($map)->order('id asc')->select();
			
			$this->assign("department", $list);
						
			$this->display();
			
		}
		
	}
	
	public function edit(){
		
		if(IS_POST){
			
			$post_data = I('post.');
			
			$post_data['department'] = json_encode($post_data['department']);
			
			$post_data['pic'] = json_encode($post_data['pic']);
			
			$data=$this->Model->create($post_data);
			
			if($data){
				
				$result = $this->Model->where(array('id'=>$post_data['id']))->update($data);
				
				if($result){
					
					echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
					
				}else{
					
					$error = $this->Model->getError();
					
					echo json_encode(array('info'=>$error, 'status'=>'n'));
					
				}
				
			}else{
				
                $error = $this->Model->getError();
				
                echo json_encode(array('info'=>$error, 'status'=>'n'));
				
			}
			
		}else{

			$info=I('get.');
			
			$info = $this->Model->where(array('id'=>$info['id']))->find();
			
			$pics = str_replace('./', '', json_decode($info['pic']));
				
			foreach($pics as $k=>$v){
					
				$data[$k] = explode(".", $v);
					
				$pic[$k]['pic'] = $v;
					
				$pic[$k]['url'] = $data[$k][0];
					
				$pic[$k]['ext'] = $data[$k][1];
					
			}
				
			$this->assign('pic', $pic);
			
			$department = json_decode($info['department']);
			
			$this->assign("department", $department);
			
			if(!empty($department)){
				
				$map['title'] = array('not in', $department);
				
			}
			
			$map['uid'] = session(C('AUTH_KEYS'));
			
			$list = M('Department')->where($map)->order('id asc')->select();
			
			$this->assign("departments", $list);
			
			$maps['uid'] = session(C('AUTH_KEYS'));
			
			$maps['title'] = array('not in', $info['management']);
			
			$lists = M('Department')->where($maps)->order('id asc')->select();
			
			$this->assign("management", $lists);
			
			$this->assign('info', $info);
						
        	$this->display();
			
		}
		
	}
	
	public function uploadify(){
		
		$type = I('post.type');
		
		$targetPath = './Public/scripts/';
		
		if(!file_exists($targetPath)){
				
			mkdir($targetPath);
				
		}
		
        $config = array(
            'maxSize' => 272629760,
            'rootPath' => './',
            'savePath' => $targetPath,
            'saveName' => array('uniqid', ''),
            'exts' => array('gif', 'jpg', 'png', 'mp4'),
            'autoSub' => true,
            'subName' => array('date', 'Ymd'),
			'saveName' => array('date', 'YmdHis'),
        );
		
		$verifyToken = md5($_POST['timestamp']);

		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
		
			$upload = new \Think\Upload($config);
			
			$info = $upload->upload();
			
			if(!$info){
				
				$arr = array(
					'status' => 0,
					'type' => $type,
					'msg' => $upload->getError()
				);
				
			}else{
				
				$ajaxname = $info['Filedata']['savepath'] . $info['Filedata']['savename'];
				
				$arr = array(
					'status' => 1,
					'type' => $type,
					'name' => $info['Filedata']['name'],
					'url' => $ajaxname
				);
				
			}
			
			echo json_encode($arr);
			
			exit;
		
		}
		
    }
	
	public function dels(){
		
		$url = I('post.name');
		
		if($url != ""){
			
    		if(unlink($url)){
				
    			$this->success("删除成功");
				
    		}else{

    			$this->error($url);
				
			}
				
    	}else{
			
    		$this->error("删除失败");
			
		}
		
	}
	
	public function copyindex(){
		
		$ids = I('get.ids');
		
		$map['id'] = array('in', $ids);
		
		$info = $this->Model->where($map)->find();
		
		$maps['sid'] = $info['id'];
			
		$maps['uid'] = $info['uid'];
			
		$maps['mid'] = $info['mid'];
		
		$infos = D('Scene')->where($maps)->select();
		
		if($info){
			
			$info['scriptsname'] = $info['scriptsname'].'-副本';
		
			$data = array(
				'scriptsname' => $info['scriptsname'],
				'range' => $info['range'],
				'brief' => $info['brief'],
				'pic' => $info['pic'],
				'goal' => $info['goal'],
				'department' => $info['department'],
				'management' => $info['management'],
				'rules' => $info['rules'],
				'uid' => $info['uid'],
				'mid' => $info['mid'],
			);
					
			$result = $this->Model->add($data);
	
			$id = $this->Model->getLastInsID();
		
			if($infos){
				
				foreach($infos as $k=>$v){
					
					$datas = array(
						'scenename' => $v['scenename'],
						'brief' => $v['brief'],
						'pic' => $v['pic'],
						'department' => $v['department'],
						'hint' => $v['hint'],
						'uid' => $v['uid'],
						'mid' => $v['mid'],
					);
					
					$results = D('Scene')->add($datas);
					
					if($results){
						
						$tid = D('Scene')->getLastInsID();
						
						$max = D('Scene')->field('MAX(tid) as tid')->find();
						
						$m['id'] = $tid;
						
						$d = array(
							'tid' => $max['tid'] + 1,
							'sid' => $id,
						);
						
						$res = D('Scene')->where($m)->save($d);
						
					}
					
				}
				
			}
			
			if($id){
					
				echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
					
			}else{
						
				$error = $this->Model->getError();
							
				echo json_encode(array('info'=>$error, 'status'=>'n'));
							
			}
			
		}
		
	}
	
	public function del(){
		
		$ids = I('get.ids');
		
        $map['id'] = array('in', $ids);
		
        $maps['sid'] =  array('in', $ids);
		
		$sql = M('Scene')->where($maps)->select();
		
		if($sql){
			
			$info = M('Scene')->where($maps)->delete();
			
			if($info){
				
				$res = $this->Model->where($map)->delete();
				
			}
			
		}else{
			
			$res = $this->Model->where($map)->delete();
			
		}
		
		if($res){
			
            echo json_encode(array('info'=>'删除成功', 'status'=>'y'));
			
        }else{
			
            $error = $this->Model->getError();
			
			echo json_encode(array('info'=>$error, 'status'=>'n'));
			
        }		
		
	}
	
	public function importdata(){
		
		if(!empty($_FILES)){
			
			$config = array(
				'maxSize' => 307200000,
				'rootPath' => './Public/excel/',
				'savePath' => '',
				'saveName' => array('date', 'YmdHis'),
				'exts' => array('xls', 'xlsx'),
				'autoSub' => true,
				'subName' => array('date', 'Y-m-d'),
			);
			
			$dir = $config['rootPath'];
			
			if(!file_exists($dir)){
				
				mkdir($dir);
				
			}
			
			$upload = new \Think\Upload($config);
			
			$info = $upload->upload();
			
			if(!$info){
				
				$this->error($upload->getError());
				
			}else{
				
				$file_name=$upload->rootPath.$info['excel']['savepath'].$info['excel']['savename'];
				
				$exts = $info['excel']['ext'];
				
				vendor("PHPExcel.PHPExcel");
				
				$objPHPExcel = new \PHPExcel();
				
				if($exts == 'xls'){
					
					$objReader = \PHPExcel_IOFactory::createReader('Excel5');
					
				}else if($exts == 'xlsx'){
					
					$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
					
				}
				
				$objPHPExcel = $objReader->load($file_name,$encode='utf-8');
				
				$sheet = $objPHPExcel->getSheet(0);
				
				$highestRow = $sheet->getHighestRow();
				
				$highestColumn = $sheet->getHighestColumn();	
				
				for($i=2; $i<=$highestRow; $i++){
										
					if($objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue()){
						
						$data['scriptsname'] = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
						
					}
					
					if($objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue()){
						
						$data['range'] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
						
					}
					
					if($objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue()){
						
						$data['brief'] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
						
					}				
					
					if($objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue()){
						
						$data['goal'] = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
						
					}
					
					if($objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue()){
						
						$data['department'] = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
						
						$data['department'] = explode(",", $data['department']);
						
						$data['department'] = json_encode($data['department']);
						
					}
					
					if($objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue()){
						
						$data['management'] = $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
						
					}
					
					if($objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue()){
						
						$data['rules'] = $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
						
					}
					
					$data['uid'] = I('post.uid');
					
					$data['mid'] = I('post.mid');
					
					if(!empty($data)){
						
						$this->Model->add($data);
						
					}
					
				}
				
				$this->success("导入数据成功");
				
			}
			
		}else{
			
			$this->error("请选择上传文件");
			
		}
		
	}
	
	public function signin(){
		
		$id = I('get.sid');
		
		$scripts = M('Scripts')->find($id);
		
		$this->assign('scripts', $scripts);
		
		$department = json_decode($scripts['department']);
		
		$this->assign('department', $department);
				
		$map['uid'] = session(C('AUTH_KEYS'));
		
		$map['mid'] = session('gid');
		
		$map['sid'] = I('get.sid');
			
		$data = M('Record')->field('MAX(pid) as pid')->where($map)->find();
		
		$pid = $data['pid'] + 1;
		
		$this->assign('pid', $pid);
		
		$this->display();
		
	}
	
	public function drill(){
		
		$map['sid'] = I('get.sid');
		
		$map['uid'] = session(C('AUTH_KEYS'));
		
		$map['mid'] = session('gid');
		
		$map['pid'] = I('get.pid');
					
		$scripts = M('Scripts')->find($map['sid']);
		
		$this->assign('scripts', $scripts);
		
		$department = json_decode($scripts['department']);
		
		$this->assign('department', $department);
		
		$scene = M('Scene')->where($map)->order('tid asc')->limit(0,1)->select();
		
		$this->assign('id', $scene[0]['id']);
		
		$record = M('Record')->where($map)->find();
		
		$this->assign('record', $record);
						
		$this->display();
		
	}
	
	public function scenario(){
		
		$map['sid'] = I('get.sid');
		
		$map['uid'] = session(C('AUTH_KEYS'));
		
		$map['mid'] = session('gid');
		
		$map['pid'] = I('get.pid');
		
		$scripts = M('Scripts')->find($map['sid']);
		
		$this->assign('scripts', $scripts);
					
		$scene = M('Scene')->where($map)->order('id asc')->select();
		
		foreach($scene as $k=>$v){
						
			$scene[$k]['hint'] = json_decode($v['hint']);
			
			$scene[$k]['pic'] = str_replace('./', '', json_decode($v['pic']));
			
			$scene[$k]['department'] = json_decode($v['department']);
			
			foreach($scene[$k]['pic'] as $k1=>$v1){
				
				$scene[$k]['pic'][$k1] = explode(".", $v1);

				$scene[$k]['pic'][$k1]['pic'] = $v1;
				
				$scene[$k]['pic'][$k1]['url'] = $scene[$k]['pic'][$k1][0];
				
				unset($scene[$k]['pic'][$k1][0]);
				
				$scene[$k]['pic'][$k1]['ext'] = $scene[$k]['pic'][$k1][1];
				
				unset($scene[$k]['pic'][$k1][1]);
				
			}
			
		}
				
		$this->assign('scene', $scene);
		
		$this->assign('department', $department);
		
		$record = M('Record')->where($map)->find();
		
		$this->assign('record', $record);

		$this->display();
		
	}
	
	public function department(){
		
		$map['sid'] = I('get.sid');
		
		$map['uid'] = session(C('AUTH_KEYS'));
		
		$map['mid'] = session('gid');
		
		$map['pid'] = I('get.pid');
		
		$map['hid'] = I('get.hid');
		
		$map['did'] = I('get.did');
		
		$map['rid'] = I('get.rid');
		
		$id = I('get.id');
		
		$scripts = M('Scripts')->find($map['sid']);
		
		$this->assign('scripts', $scripts);
		
		$id = I('get.hid');
			
		$scene = M('Scene')->find($id);
		
		$this->assign('scene', $scene);
		
		$data = M('Hint')->field('MAX(cid) as cid')->where($map)->find();
		
		$cid = $data['cid'] + 1;
		
		$this->assign('cid', $cid);
		
		$this->display();
		
	}
	
	public function starts(){
		
		$post_data = I('post.');
		
		$post_data['start_time'] = time();
		
		$res = M('Hint')->add($post_data);		
				
		if($res){
					
			echo json_encode(array('info'=>'操作成功', 'status'=>'y', 'id'=>$res) );
					
		}else{
					
			echo json_encode(array('info'=>$error, 'status'=>'n'));
					
		}
			
	}
			
	public function acceptfile(){
		
		error_reporting(0);
		
    	try{
        	$name = time().rand(1000, 9999);
			
			$upload_path = './Public/voice/';
			
			if(!file_exists($upload_path)){
				
				mkdir($upload_path);
				
			}
		
			$upload_filename =	$upload_path.$name;
        
			$fp = fopen($upload_filename . '.mp3', "wb");

        	fwrite($fp, file_get_contents('php://input'));

        	fclose($fp);

        	exit($name . ".mp3");
			
    	}catch (Exception $e) {
			
        	exit;
			
    	}
		
	}
	
	public function result(){
		
		$map['sid'] = I('get.sid');
		
		$map['uid'] = session(C('AUTH_KEYS'));
		
		$map['mid'] = session('gid');
		
		$scripts = M('Scripts')->find($map['sid']);
		
		$this->assign('scripts', $scripts);
		
		$department = json_decode($scripts['department']);
		
		$this->assign('department', $department);
				
		$scene = M('Scene')->where($map)->find();
		
		$this->assign('scene', $scene);
				
		$maps['sid'] = I('get.sid');
		
		$maps['uid'] = session(C('AUTH_KEYS'));
		
		$maps['mid'] = session('gid');
		
		$maps['pid'] = I('get.pid');
		
		$record = M('Record')->where($maps)->find();
				
		$this->assign('record', $record);
		
		$this->display();
		
	}
	
	public function report(){
		
		$map['sid'] = I('get.sid');
		
		$map['uid'] = session(C('AUTH_KEYS'));
		
		$map['mid'] = session('gid');
		
		$map['pid'] = I('get.pid');
		
		$map['hid'] = I('get.hid');
		
		$map['did'] = I('get.did');
		
		$map['rid'] = I('get.rid');
				
		$scripts = M('Scripts')->find($map['sid']);
		
		$this->assign('scripts', $scripts);
		
		$data = M('Report')->field('MAX(cid) as cid')->where($map)->find();
		
		$cid = $data['cid'] + 1;
		
		$this->assign('cid', $cid);
		
		$this->display();
		
	}
	
	public function voice(){
		
		header('Content-Type: audio/mpeg');
		
		$sid = I('get.sid');
		
		$pid = I('get.pid');
		
		$bid = I('get.bid');
		
		$nid = I('get.nid');
		
		$this->assign('nid', $nid);
		
		$tid = I('get.tid');
		
		$this->assign('tid', $tid);
		
		if($bid == "scripts"){
		
			$info = M('Scripts')->where(array('id'=>$sid))->find();
			
			$text = $info[$nid];
		
		}
		
		if($bid == "scene"){
		
			$info = M('Scene')->where(array('id'=>$sid))->find();
			
			if($nid == "hint"){
				
				$hint = json_decode($info[$nid]);
				
				$text = implode(",",$hint);
				
			}else{
				
				$text = $info[$nid];
				
			}
		
		}

		//$url = "http://api.satori.moe/text2audio.php?text=$text";
		$text = urlencode(urlencode($text));
		$url = "http://tsn.baidu.com/text2audio?tex=$text&tok=24.6bbf3be1038b4c8cb5b851e159ed0064.2592000.1538233090.282335-11752112&lan=zh&cuid=08:00:27:9F:BD:99&ctp=1";
		
		$get = file_get_contents($url);
		
		echo $get;
		
	}

	public function h5acceptfile(){
        	
		header("Access-Control-Allow-Origin: *");
		if (!isset($_POST['audio-filename']) && !isset($_POST['video-filename'])) {
			echo 'PermissionDeniedError';
			return;
		}

		$fileName = '';
		$tempName = '';

		if (isset($_POST['audio-filename'])) {
			$fileName = $_POST['audio-filename'];
			$tempName = $_FILES['audio-blob']['tmp_name'];
		} else {
			$fileName = $_POST['video-filename'];
			$tempName = $_FILES['video-blob']['tmp_name'];
		}

		if (empty($fileName) || empty($tempName)) {
			echo 'PermissionDeniedError';
			return;
		}
		$filePath = 'Public/voice/' . $fileName;

		// make sure that one can upload only allowed audio/video files
		$allowed = array(
			'webm',
			'wav',
			'mp4',
			'mp3',
			'ogg'
		);
		$extension = pathinfo($filePath, PATHINFO_EXTENSION);

		if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
			echo 'PermissionDeniedError';
			//continue;
			return;
		}

		if (!move_uploaded_file($tempName, $filePath)) {
			echo ('Problem saving file.');
			return;
		}

		echo ($filePath);

	
	}
		
}
